import { createSlice } from "@reduxjs/toolkit"
import { Toast } from "antd-mobile"

export const personSlice = createSlice({
  name: "person",
  initialState: {
    personList: [
      {
        id: 1,
        name: "马大姐",
        code: "265626446615464",
        phone: "17658925586",
        status: false,
      },
      {
        id: 2,
        name: "章小蕊",
        code: "98958855962592",
        phone: "18958855995",
        status: false,
      },
      {
        id: 3,
        name: "糖人",
        code: "8989546626226656",
        phone: "18965628582",
        status: false,
      },
      {
        id: 4,
        name: "刘书鸿",
        code: "145244525632566",
        phone: "17652940018",
        status: false,
      },
    ],
  },
  reducers: {
    // 选择乘车人
    selectedPerosn(state, { payload }) {
      // 查找选中的id和仓库里的哪一个id相同
      const result = state.personList.find(item => item.id == payload.id)
      if (result) {
        result.status = !result.status
      }
    },
    // 删除乘车人
    deletePerson(state, { payload }) {
      // 过滤掉不相同的id
      const filretData = state.personList.filter(item => item.id !== payload.id)
      state.personList = filretData
    },
    // 新增乘车人
    addPerson(state, { payload }) {
      // 查找选中的id和仓库里的哪一个id相同
      const result = state.personList.find(item => item.id == payload.id)
      if (result) {
        Toast.show("乘车人已存在")
        return
      } else {
        Toast.show({
          content: "添加成功",
          icon: "success",
        })
        // 保留原有值添加新的值
        state.personList = [...state.personList, payload]
      }
    },
    // 编辑乘车人
    editPerson(state, { payload }) {
      // 查找选中的id和仓库里的哪一个id相同
      const result = state.personList.some(item => item.id == payload.id)
      if (result) {
        Toast.show({
          content: "添加成功",
          icon: "success",
        })
        // 相同属性名第二参数替换第一参数的属性值
        Object.assign(...state.personList, payload)
      }
    },
  },
})
// 每个 case reducer 函数会生成对应的 Action creators
export const { selectedPerosn, deletePerson, addPerson, editPerson } =
  personSlice.actions

export default personSlice.reducer
